#include "Communication.hpp"
#include <iostream>
#include <cstdlib>


int main(int argc, char *argv[])
{
	list<Host> all;
	list<string> name;
	Host one;
	one.port = 10000;
	Communication comm;
	if(false){
		one.name = "localhost";
		for(int i = 0; i < 3; i++){
			all.push_back(one);
			one.port++;
		}
		int me = atoi(argv[1]);
		cout << "ID = " << me << endl;
		comm = Communication(all, me < 0, me < 0 ? 0 : me);
	}else{
		one.name = "net00.utdallas.edu";
		for(int i = 0; i < 3; i++){
			one.name[4] = '1' + i;
			name.push_back(one.name);
			all.push_back(one);
		}
		int isserver = 0;
		if(whoami(name) == 0){
			cout << "You are the first node, are you the server?";
			cin >> isserver;
		}
		comm = Communication(all, isserver);
	}
	cout <<
		"** This is a command line without error detection. Don't make mistakes!\n"
		"All possible commands:\n"
		"e\t\tIncrement the vector clock\n"
		"p\t\tPrint current vector clock\n"
		"s i d str\tSend message str to node i with delivery time d, if i==-1, broadcast, if i==-2, to server\n"
		"r t\t\tReceive messages and pretend the time is t\n"
		"Again, don't make any mistakes, otherwise the behavior is undefined."
	     << endl;
	Message msg;
	char c;
	unsigned now;
	int s;
	while(true){
		cout << "? ";
		cin >> c;
		switch(c){
		case 's':
			cin >> msg.node >> msg.deliv;
			cin.ignore();
			getline(cin, msg.data);
			cout << "Sending message: " << (string) msg << endl;
			comm.send(msg);
			break;
		case 'r':
			cin >> now;
			cout << "Receiving message at " << now << endl;
			s = comm.recv(msg,now);
			if(s < 0){
				cout << "Message from node " << msg.node << ": " << msg.data << endl;
				s = -s - 1;
			}else
				cout << "No message to deliver" << endl;
			cout << s << " messages remaining in the queue" << endl;
			break;
		case 'e':
			comm.event();
		case 'p':
			cout << "Current clock: " << (string)comm.clock() <<endl;
			break;
		default:
			break;
		}
	}
}
